import { Controller, Get, Post, Put, Delete, Param, Body, Query, HttpException, HttpStatus } from '@nestjs/common';
import { SourceService } from './source.service';
import { BookSource } from './source.entity';
import { SourceParserService } from './source-parser.service';

@Controller('sources')
export class SourceController {
  constructor(
    private readonly sourceService: SourceService,
    private readonly sourceParserService: SourceParserService,
  ) {}

  // 获取所有书源
  @Get()
  async getAll(): Promise<BookSource[]> {
    return this.sourceService.findAll();
  }

  // 根据 ID 获取单个书源详情
  @Get(':id')
  async getOne(@Param('id') id: string): Promise<BookSource> {
    return this.sourceService.findOne(+id);
  }

  // 新增书源
  @Post()
  async create(@Body() data: Partial<BookSource>): Promise<BookSource> {
    return this.sourceService.create(data);
  }

  // 更新书源
  @Put(':id')
  async update(
    @Param('id') id: string,
    @Body() data: Partial<BookSource>,
  ): Promise<BookSource> {
    return this.sourceService.update(+id, data);
  }

  // 删除书源
  @Delete(':id')
  async remove(@Param('id') id: string): Promise<void> {
    return this.sourceService.remove(+id);
  }

  /**
   * 根据指定书源和小说页面 URL 通过新规则爬取小说数据  
   * 接口示例： GET /sources/novel/1?url=https://www.example.com/novel/12345
   */
  @Get('/novel/:sourceId')
  async crawlNovelBySource(
    @Param('sourceId') sourceId: string,
    @Query('url') novelUrl: string,
  ): Promise<any> {
    const source = await this.sourceService.findOne(+sourceId);
    if (!source) {
      throw new HttpException('书源不存在', HttpStatus.NOT_FOUND);
    }
    if (!novelUrl) {
      throw new HttpException('必须提供小说页面 URL', HttpStatus.BAD_REQUEST);
    }
    // 这里假设 source.rules 存储了新的规则（包含 ruleBookInfo, ruleToc, ruleContent 等）
    const rules = source.rules || {};
    try {
      const result = await this.sourceParserService.crawlNovelByRules(novelUrl, rules);
      return result;
    } catch (error) {
      throw new HttpException(`爬取小说数据失败: ${error.message}`, HttpStatus.BAD_GATEWAY);
    }
  }
} 